# @Time : 2021/4/7 10:43
# @Author : Fioman 
# @Phone : 13149920693
"""
数据库管理工具,备份和删除之类的
"""
import os
import subprocess
from settings import DATA_BASE_DUMP_DIR, DATA_BASE_IMPORT_DIR, DATABASE_NAME

IP = '127.0.0.1'


def get_dump_dir():
    """
    获取数据库环境变量的备份打包命令的绝对目录
    :return:成功返回目录,失败返回None
    """

    pathEnviron = ""
    for a, b in os.environ.items():
        if a == "PATH":
            pathEnviron = b
            pathEnviron = pathEnviron.split(";")
    mongdbPath = None
    for path in pathEnviron:
        if "MongoDB" in path and "bin" in path:
            mongdbPath = path
    return mongdbPath


# 备份数据库
def dump_data():
    """
    备份数据库,默认保存到d盘的db_data_copy目录下面,如果没有这个目录就创建一个
    :return:
    """
    dataKeepDir = DATA_BASE_DUMP_DIR
    # 先去获取环境变量里面的bin目录.
    dumpDir = get_dump_dir()
    if dumpDir is None:
        return "备份失败,MongoDB没有加入到系统换将变量中"
    else:
        dumpPath = os.path.join(dumpDir, 'mongodump')  # 备份命令路径
        dumpCmd = "{} -h {}:27017 --db {} --excludeCollection=image_data.chunks " \
                  "--excludeCollection=image_data.files  -o {}".format(dumpPath, IP, DATABASE_NAME, dataKeepDir)  # 执行的复制命令
        try:
            ps = subprocess.Popen(dumpCmd)
            res = ps.wait()
            return 'ok' if res == 0 else '备份数据失败,请检查命令路径是否配置正确!'
        except RuntimeError as e:
            return e


def import_data():
    """
    数据库导入
    :return:
    """
    dataImportDir = DATA_BASE_IMPORT_DIR
    # 先去获取环境变量里面的bin目录.
    importDir = get_dump_dir()
    if importDir is None:
        return "数据导入失败,MongoDB没有加入到系统换将变量中"
    else:
        importPath = os.path.join(importDir, 'mongorestore')  # 备份命令路径
        restoreCmd = "{} -h {}:27017 --drop --dir {}".format(importPath, IP, dataImportDir)  # 执行的复制命令
        try:
            ps = subprocess.Popen(restoreCmd)
            res = ps.wait()
            return 'ok' if res == 0 else '数据导入失败,请确保导入的数据在 {} 目录中!'.format(dataImportDir)
        except RuntimeError as e:
            return e


if __name__ == '__main__':
    res2 = import_data()
